package com.inspectionwork.web.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inspectionwork.common.base.BaseService;
import com.inspectionwork.model.*;
import com.inspectionwork.support.model.RespEntity;
import com.inspectionwork.support.utils.requestutil.HttpRequestUtil;
import com.inspectionwork.web.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class NoticeannouncementService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(InspectionworkService.class);

    @Resource
    private NoticeAnnouncementMapper noticeAnnouncementMapper;
    @Resource
    private RelevantFilesMapper relevantFilesMapper;
    @Resource
    private RelevantUnitsMapper relevantUnitsMapper;
    @Resource
    private UseDictMapper useDictMapper;
    @Resource
    private BusinessMapper businessMapper;

    /**
     * 通知公告的列表查询
     *
     * @param
     * @return
     */
    public RespEntity listNoticeAnnouncementListPage(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        Page<DeviceBusiness> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        IPage<NoticeAnnouncement> pageList = null;
        jsonParam.put("homeId", homeId);
        if (userType.equals("1")) {//为机构用户
            pageList = noticeAnnouncementMapper.noticeAnnouncementListPageForOrg(page, jsonParam);
        } else if (userType.equals("2")) {//为单位用户
            pageList = noticeAnnouncementMapper.noticeAnnouncementListPageForBu(page, jsonParam);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    /**
     * 通知公告的新增或修改
     *
     * @param
     * @return
     */
    public RespEntity addOrUpdate(JSONObject jsonParam) throws Exception {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String uuid = "";
        if (!jsonParam.getBool("ishaveReceivingUnit")) {
            return RespEntity.fail("没有接收单位");
        }
        NoticeAnnouncement noticeAnnouncement = new NoticeAnnouncement();
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))) {//修改
            uuid = jsonParam.getStr("id");
            NoticeAnnouncement temp = noticeAnnouncementMapper.selectById(jsonParam.getStr("id"));
            if (temp == null) return RespEntity.fail("传入的id错误");
            if (temp.getState()) {
                return RespEntity.fail("已发布，不能修改");
            } else {
                //删除附件表和接收单位表的相关信息
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("relevant_id", temp.getId());
                relevantUnitsMapper.deleteByMap(deleteMap);
                relevantFilesMapper.deleteByMap(deleteMap);
            }
        } else {//新增
            uuid = UUID.randomUUID().toString();
            noticeAnnouncement.setCreatePersonId(userId);
            noticeAnnouncement.setIsDel(false);
            noticeAnnouncement.setCreatetime(new Date());
            noticeAnnouncement.setOrgId(homeId);
            noticeAnnouncement.setOrgName(jsonParam.getStr("homeName"));
        }
        //保存通知公告
        noticeAnnouncement.setId(uuid);
        noticeAnnouncement.setName(jsonParam.getStr("name"));
        noticeAnnouncement.setContacts(jsonParam.getStr("contacts"));
        noticeAnnouncement.setAnnouncementType(jsonParam.getStr("announcementType"));
        noticeAnnouncement.setContentDes(jsonParam.getStr("contentDes"));
        noticeAnnouncement.setState(jsonParam.getBool("state"));
        if (jsonParam.getBool("state")) noticeAnnouncement.setPublishtime(new Date());
        noticeAnnouncement.setIshaveReceivingUnit(jsonParam.getBool("ishaveReceivingUnit"));
        noticeAnnouncement.setIshaveFile(jsonParam.getBool("ishaveFile"));
        if (jsonParam.getBool("ishaveReceivingUnit")) {//如果有接收单位
            if (jsonParam.getBool("allflag")) {//如果是选择了下辖所有单位
                noticeAnnouncement.setAllflag(jsonParam.getBool("allflag"));
                noticeAnnouncement.setBottomArea(jsonParam.getStr("bottomArea"));
                //rest请求单位详情接口，获取单位信息
                JSONObject jsonParamN = new JSONObject();
                jsonParamN.put("bottomArea", jsonParam.getStr("bottomArea"));
                com.alibaba.fastjson.JSONObject allAreas = makeDataForToken(jsonParamN, "businessJava", "config", "getAllArea", "alarmInfo");
                if (StrUtil.isNotBlank(allAreas.getString("methodErrorFlag")))
                    return RespEntity.fail(allAreas.getString("msg"));
                String allArea = allAreas.getString("allArea");
                noticeAnnouncement.setArea(allArea);
                //根据机构id和区划，获取所有单位的信息，保存到接收单位表中
                jsonParamN = new JSONObject();
                jsonParamN.put("orgId", homeId);
                jsonParamN.put("area", allArea.startsWith(",") ? allArea.substring(1, allArea.length()) : allArea);
                JSON businessListJson = makeDataForJSONForToken(jsonParamN, "businessJava", "config", "businessList", "alarmInfo");
                if (businessListJson instanceof com.alibaba.fastjson.JSONObject) {
                    com.alibaba.fastjson.JSONObject checkaddrRecordListJsonN = (com.alibaba.fastjson.JSONObject) businessListJson;
                    if (StrUtil.isNotBlank(checkaddrRecordListJsonN.getString("methodCodeFlag"))) {
                        return RespEntity.expire();
                    }
                    return RespEntity.fail(((com.alibaba.fastjson.JSONObject) businessListJson).getString("msg"));
                } else {
                    JSONArray businessList = (JSONArray) businessListJson;
                    List<RelevantUnits> buList = new ArrayList<>();
                    for (Object ob : businessList) {
                        com.alibaba.fastjson.JSONObject business = (com.alibaba.fastjson.JSONObject) ob;
                        RelevantUnits relevantUnits = new RelevantUnits();
                        relevantUnits.setIsworkable(false);
                        relevantUnits.setReceivingUnitId(business.getString("id"));
                        relevantUnits.setReceivingUnitName(business.getString("name"));
                        relevantUnits.setRelevantId(uuid);
                        relevantUnits.setWorkabletime(null);
                        buList.add(relevantUnits);
                    }
                    //批量保存接收单位
                    if (buList.isEmpty()) {
                        return RespEntity.fail("此区域没有接收单位");
                    }
                    noticeAnnouncementMapper.insertAllUnits(buList);
                }
            } else {//如果不是选择下辖所有单位
                noticeAnnouncement.setAllflag(jsonParam.getBool("allflag"));
                //根据组装好的id数组，获取所有单位的信息，保存到接收单位表中
                String units = jsonParam.getStr("units");
                String[] unitList = units.split(",");
                List<String> list = Arrays.asList(unitList);
                List<Business> businessList = businessMapper.selectBatchIds(list);
                if (businessList.isEmpty()) {
                    return RespEntity.fail("没有接收单位");
                }
                List<RelevantUnits> buList = new ArrayList<>();
                for (Business business : businessList) {
                    RelevantUnits relevantUnits = new RelevantUnits();
                    relevantUnits.setIsworkable(false);
                    relevantUnits.setReceivingUnitId(business.getId());
                    relevantUnits.setReceivingUnitName(business.getName());
                    relevantUnits.setRelevantId(uuid);
                    relevantUnits.setWorkabletime(null);
                    buList.add(relevantUnits);
                }
                //批量保存接收单位
                noticeAnnouncementMapper.insertAllUnits(buList);
            }
        }
        if (jsonParam.getBool("ishaveFile")) {//如果有附件
            RelevantFiles relevantFiles = new RelevantFiles();
            relevantFiles.setFileName(jsonParam.getStr("fileName"));
            relevantFiles.setFilePath(jsonParam.getStr("filePath"));
            relevantFiles.setRelevantId(uuid);
            relevantFilesMapper.insert(relevantFiles);
        }
        if (jsonParam.containsKey("id") && StrUtil.isNotBlank(jsonParam.getStr("id"))) {//修改
            noticeAnnouncementMapper.updateById(noticeAnnouncement);
        } else {//新增
            noticeAnnouncementMapper.insert(noticeAnnouncement);
        }
        return RespEntity.success();
    }

    /**
     * 通知公告的删除
     *
     * @param
     * @return
     */
    public RespEntity delete(JSONObject jsonParam) {
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        NoticeAnnouncement noticeAnnouncement = noticeAnnouncementMapper.selectById(jsonParam.getStr("id"));
        if (noticeAnnouncement == null) return RespEntity.fail("通知公告不存在!");
        if (noticeAnnouncement.getState() && !homeId.equals("001e7548-8735-4b31-b30b-c9361a62c102"))
            return RespEntity.fail("已发布，不能删除!");
        //删除附件表和接收单位表的相关信息
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("relevant_id", noticeAnnouncement.getId());
        relevantUnitsMapper.deleteByMap(deleteMap);
        relevantFilesMapper.deleteByMap(deleteMap);
        //更新删除这条通知公告
        NoticeAnnouncement announcement = new NoticeAnnouncement();
        announcement.setIsDel(true);
        announcement.setId(jsonParam.getStr("id"));
        noticeAnnouncementMapper.updateById(announcement);
        return RespEntity.success();
    }

    /**
     * 字典表查询
     *
     * @param
     * @return
     */
    public RespEntity dictList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        List<UseDict> dictlist = useDictMapper.selectList(new QueryWrapper<UseDict>().eq("groupname", jsonParam.getStr("groupname")).orderByAsc("sortid"));
        return RespEntity.success(dictlist);
    }

    /**
     * 通知公告详情
     *
     * @param
     * @return
     */
    public RespEntity getById(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        //通知公告详情
        NoticeAnnouncement noticeAnnouncement = noticeAnnouncementMapper.selectById(jsonParam);
        if (noticeAnnouncement == null) {
            return RespEntity.fail("传入的id错误");
        }
        UseDict useDict = useDictMapper.selectById(noticeAnnouncement.getAnnouncementType());
        if (useDict != null) {
            noticeAnnouncement.put("announcementTypeName", useDict.getName());
        }
        //如果ishaveFile=1,获取图片名字和路径
        if (noticeAnnouncement.getIshaveFile()) {
            Map<String, Object> fileMap = noticeAnnouncementMapper.getFileField(jsonParam);
            noticeAnnouncement.put("fileName", fileMap.get("fileName") == null ? "" : fileMap.get("fileName"));
            noticeAnnouncement.put("filePath", fileMap.get("filePath") == null ? "" : fileMap.get("filePath"));
        }
        if (noticeAnnouncement.getIshaveReceivingUnit()) {
            if (!noticeAnnouncement.isAllflag()) {//当allflag=0时,列出选择的单位返回；当allflag=1时，不做下边操作，前端直接显示下辖所有单位
                List<RelevantUnits> relevantUnitsList = noticeAnnouncementMapper.receivingUnitList(jsonParam);
                String receivingUnitIds = "";
                String receivingUnitNames = "";
                for (RelevantUnits relevantUnits : relevantUnitsList) {
                    receivingUnitIds = receivingUnitIds + relevantUnits.getReceivingUnitId() + ",";
                    receivingUnitNames = receivingUnitNames + relevantUnits.getReceivingUnitName() + ",";
                }
                if (StrUtil.isNotBlank(receivingUnitIds))
                    receivingUnitIds = receivingUnitIds.substring(0, receivingUnitIds.length() - 1);
                if (StrUtil.isNotBlank(receivingUnitNames))
                    receivingUnitNames = receivingUnitNames.substring(0, receivingUnitNames.length() - 1);
                noticeAnnouncement.put("receivingUnitIds", receivingUnitIds);
                noticeAnnouncement.put("receivingUnitNames", receivingUnitNames);
            }
        }
        return RespEntity.success(noticeAnnouncement);
    }

    /**
     * @Author YangYu
     * @Description 通知公告下发删除
     * @Date Created in 13:39 2024/5/11
     * @Param [jsonParam]
     */

    public RespEntity deleteById(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String id = jsonParam.getStr("id");
        int noticeAnnouncement = this.noticeAnnouncementMapper.deleteById(jsonParam.getStr("id"));
        int relevantFiles = this.relevantFilesMapper.delete(new QueryWrapper<RelevantFiles>().eq("relevant_id", jsonParam.getStr("id")));
        int relevantUnits = this.relevantUnitsMapper.delete(new QueryWrapper<RelevantUnits>().eq("relevant_id", jsonParam.getStr("id")));
        if (noticeAnnouncement > 0 && relevantFiles > 0 && relevantUnits > 0) {
            return RespEntity.success();
        }
        return RespEntity.fail();
    }

    /**
     * @Author YangYu
     * @Description 工作管理信息统计
     * @Date Created in 13:39 2024/5/11
     * @Param [jsonParam]
     */

    public RespEntity workCount(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userType = token.getString("user_type");
        QueryWrapper<NoticeAnnouncement> queryWrapper = new QueryWrapper<>();
        if (userType.equals("1")){
            queryWrapper.select("announcement_type","COUNT(announcement_type) as count")
                    .eq("org_id",homeId)
                    .eq("is_del",0)
                    .groupBy("announcement_type");
        }else {
            List<Object> results = relevantUnitsMapper.selectObjs(new QueryWrapper<RelevantUnits>().select("relevant_id").eq("receiving_unit_id",homeId));
            List<String> idList = results.stream().map(Object::toString).collect(Collectors.toList());

            queryWrapper.select("announcement_type","COUNT(announcement_type) as count")
                    .in("id",idList)
                    .eq("is_del",0)
                    .groupBy("announcement_type");
        }
        List<NoticeAnnouncement> noticeAnnouncementList = noticeAnnouncementMapper.selectList(queryWrapper);
        // 工作通知统计
        int workCount = 0;
        // 安全通报统计
        int securityCount = 0;
        // 待办任务统计
        int tasksCount = 0;
        for (NoticeAnnouncement noticeAnnouncement : noticeAnnouncementList){
            if (noticeAnnouncement.getAnnouncementType().equals("001e7548-8735-4b31-b30b-c9361a62c910")){
                workCount = noticeAnnouncement.getInt("count");
            }else if (noticeAnnouncement.getAnnouncementType().equals("001e7548-8735-4b31-b30b-c9361a62c911")){
                securityCount = noticeAnnouncement.getInt("count");
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tasksCount",tasksCount);
        jsonObject.put("workCount",workCount);
        jsonObject.put("securityCount",securityCount);
        return RespEntity.success(jsonObject);
    }

}
